﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace _3DSensor
{
    public class Util
    {
        /// <summary>
        /// starts a process only if no other instance is active/running
        /// </summary>
        /// <param name="appName"></param>
        /// <returns></returns>
        public static Process startProcess(string appName)
        {
            Boolean exists = false;
            int pId = -1;
            exists = processExists(appName, out pId);
            if (!exists)
            {
                Process p = System.Diagnostics.Process.Start(appName);
                return p;
            }
            else return null;
        }
        /// <summary>
        /// kills a process (only after ascertaining that it is on/running)
        /// </summary>
        /// <param name="appName"></param>
        public static void killProcess(string appName)
        {
            Boolean exists = false;
            int pId = -1;
            exists = processExists(appName, out pId);
            if (exists)
            {
                try
                {
                    System.Diagnostics.Process.GetProcessById(pId).Kill();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception: " + e.Message + "\n" + e.StackTrace);
                }
            }
        }

        /// <summary>
        /// checks if a process exists and provides the pid of the same
        /// </summary>
        /// <param name="appName"></param>
        /// <param name="pId"></param>
        /// <returns></returns>
        public static Boolean processExists(string appName, out int pId)
        {
            bool exists = false;
            pId = -1;
            appName = appName.Substring(0, appName.IndexOf("."));
            Process[] processes = Process.GetProcesses();
            foreach (Process p in processes)
            {
                if (p.ProcessName.Equals(appName))
                {

                    pId = p.Id;
                    exists = true;
                    break;
                }
            }
            return exists;
        }

    }
}
